package com.zhang.bingmei_incomeexpenditure.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhang.bingmei_incomeexpenditure.entity.comCity.CommCity;
import com.zhang.bingmei_incomeexpenditure.service.CommCityService;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping("/city-file")
public class CityFileController {

    @Resource
    private CommCityService commCityService;

    // Jackson ObjectMapper用于JSON序列化
    private final ObjectMapper objectMapper = new ObjectMapper();

    // 基础文件路径
    private static final String BASE_FILE_PATH = "E:\\file\\";

    /**
     * 将城市数据保存到JSON文件
     * http://localhost:8181/city-file/save-to-file
     */
    @GetMapping("/save-to-file")
    public String saveCitiesToFile() {
        try {
            // 1. 获取所有城市数据
            List<CommCity> cities = commCityService.list();

            if (cities == null || cities.isEmpty()) {
                return "没有获取到城市数据";
            }else{
                cities.stream().forEach(System.out::println);
            }

            // 2. 生成带时间戳的文件名
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String timestamp = LocalDateTime.now().format(formatter);
            String fileName = "city_data_" + timestamp + ".json";
            String filePath = BASE_FILE_PATH + fileName;

            // 3. 检查并创建目录
            File directory = new File(BASE_FILE_PATH);
            if (!directory.exists()) {
                if (!directory.mkdirs()) {
                    return "创建目录失败：" + BASE_FILE_PATH;
                }
            }

            // 4. 将数据转换为格式化的JSON字符串
            String jsonData = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(cities);

            // 4. 写入文件
            try (FileWriter fileWriter = new FileWriter(filePath);
                 PrintWriter printWriter = new PrintWriter(fileWriter)) {
                printWriter.write(jsonData);
            }

            return "城市数据已成功保存到文件：" + filePath + "\n共保存 " + cities.size() + " 条记录";

        } catch (JsonProcessingException e) {
            return "JSON序列化失败：" + e.getMessage();
        } catch (IOException e) {
            return "文件写入失败：" + e.getMessage();
        } catch (Exception e) {
            return "保存数据时发生未知错误：" + e.getMessage();
        }
    }

    @GetMapping("/export")
    public String exportCitiesToFile() {

        List<CommCity> dataList = commCityService.list();

        // 创建BufferedWriter对象
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
// 遍历List并写入文件
            for (CommCity data : dataList) {
                bw.write(String.valueOf(data));
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "导出数据失败：" + e.getMessage();
        }
        return "数据已成功导出到output.txt文件";
    }

}
